import {createRouter, createWebHistory, type RouteRecordRaw} from "vue-router";
import type {MenuTreeItem} from "@/type/common/MenuRouter";
import {MainMenuItems} from "@/main";
import {getMenuList} from '@/api/system/menu';
import {buildMenuTree} from '@/utils/routerUtils';
import {message} from '@/utils/ElmessasgeUtils';

// 预加载所有 views 下的 vue 文件
const modules = import.meta.glob('@/views/**/*.vue');

export function filterMenus(menus: MenuTreeItem[], types: number[]): MenuTreeItem[] {
    return menus
        .filter(menu => types.includes(menu.type) && menu.active)
        .map(menu => {
            if (menu.children && menu.children.length > 0) {
                return {
                    ...menu,
                    children: filterMenus(menu.children, types)
                };
            }
            return {...menu};
        });
}

export function filterMenusNotIn(menus: MenuTreeItem[], types: number[]): MenuTreeItem[] {
    return menus
        .filter(menu => !(types.includes(menu.type) && menu.active))
        .map(menu => {
            if (menu.children && menu.children.length > 0) {
                return {
                    ...menu,
                    children: filterMenusNotIn(menu.children, types)
                };
            }
            return {...menu};
        });
}

// 生成动态路由
function generateRoutes(menuItems: any[]): RouteRecordRaw[] {
    return menuItems.map(item => {
        let redirectPath = item.redirect;
        if (item.children && item.children.length > 0) {
            const firstActiveChild = item.children[0];
            if (!redirectPath && firstActiveChild) {
                redirectPath = firstActiveChild.router;
            }
        }

        const route: RouteRecordRaw = {
            path: item.router,
            name: item.title,
            component: item.componentPath
                ? modules[`/src/views/${item.componentPath}`]
                : undefined,
            redirect: redirectPath,
            meta: {
                id: item.id,
                title: item.title,
                type: item.type,
                icon: item.icon || null,
                count: item.count || 0,
            },
            children: item.children ? generateRoutes(item.children) : []
        };

        return route;
    });
}

// 静态路由
const staticRouters: RouteRecordRaw[] = [
    {
        path: "/login",
        name: "Login",
        component: () => import("@/views/Login.vue"),
        meta: {title: "登录"}
    },
    {
        path: '/404',
        name: '404',
        component: () => import('@/views/404.vue')
    },
    {
        path: '/',
        name: 'Home',
        component: () => import('@/views/Index.vue'),
        redirect: '', // 先设置为空，动态路由加载后更新
        children: [] // 初始化空子路由，用于后续添加动态路由
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/404'
    }
];

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes: [...staticRouters]
});

console.log("初始路由", router.getRoutes());

// 获取菜单并添加动态路由的函数
export async function loadDynamicMenus() {
    try {
        const res: any = await getMenuList();
        if (res.data.code == 200) {
            MainMenuItems.value = buildMenuTree(res.data.data);
            // 过滤出激活路由
            const filteredActiveMenus = filterMenus(MainMenuItems.value, [1, 2, 6, 11]);
            const dynamicRoutes = generateRoutes(filteredActiveMenus);

            // 查找根路由
            const rootRoute = router.getRoutes().find(route => route.name === 'Home');

            if (rootRoute) {
                // 将动态路由添加为根路由的子路由
                dynamicRoutes.forEach(route => {
                    if (!router.hasRoute(route.name as string)) {
                        router.addRoute('Home', route);
                    } else {
                        console.log(`路由已存在: ${route.path}`);
                    }
                });

                // 更新根路由的redirect，指向第一个子路由
                if (dynamicRoutes.length > 0) {
                    const firstChildRoute = dynamicRoutes[0];
                    // 移除现有的根路由并重新添加带有redirect的新路由
                    router.removeRoute('Home');
                    router.addRoute({
                        path: '/',
                        name: 'Home',
                        component: () => import('@/views/Index.vue'),
                        redirect: firstChildRoute.path, // 重定向到第一个子路由
                        children: dynamicRoutes
                    });
                    console.log(`根路由已重定向到: ${firstChildRoute.path}`);
                }

                console.log("动态加载路由后：", router.getRoutes());
                return true;
            } else {
                console.error("未找到根路由 'Home'");
                return false;
            }
        } else {
            message("获取菜单列表失败", 'error');
            return false;
        }
    } catch (error) {
        console.error("加载菜单失败:", error);
        message("加载菜单失败", 'error');
        return false;
    }
}

export default router;